<?php

namespace app\admin\model;
use think\Model;
use app\admin\model\AdminLog;
use Exception;
use think\Log;

/*
 * 金蝶api
 *   */
class Kisapi extends Model
{
    protected $name = "kis_api_log";
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    
    //固定token也可，目前不过期
    protected $token = '';
    
    /**
     * @var string app_key
     */
    protected static $user_name = 'admin';
    
    /**
     * @var string app_secret
     */
    protected static $user_secret = 'wms123456.';
    
    
    /* public static function getToken($user_id){
        if(!$token){
            exception('获取token失败');
        }
        
        return $token;
    } */
    
    public static function getToken(){
        $token = session('u8_api_token');
        if(!$token){
            $res = self::getDataByName('login',[
                "Username" => self::$user_name,
                "Password" => self::$user_secret
            ]);
            if(isset($res['token'])&&$res['token']){
                session('u8_api_token',$res['token']);
                $token = $res['token'];
            }
        }

        if(!$token){
            exception('获取token失败');
        }
        
        return $token;
    }
    /*
     * 根据name获取api数据
     * {
        PageSize:1,
        PageIndex:1,
       }
     *   */
    public static function getDataByName($name = '',$data = [],$pageflag = false,$logflag = false){
        $api = '';
        if(!$data){
            //默认返回全部
            $data['PageSize'] = 9999;
            $data['PageIndex'] = 1;
        }
        
        switch ($name){
            case 'login':
                $api = '/api/Login/SignIn';
                break;
            case 'user':
                $api = '/api/getUsers';
            break;
            case 'warehouse':
                $api = '/api/getStock';
            break;
            case 'inventory':
                $api = '/api/getIcItem';
            break;
            case 'unit':
                $api = '/api/getUnit';
            break;
            case 'inventoryclass':
                $api = '/api/getIcItemClass';
            break;
            case 'customer'://客户
                $api = '/api/getCustomer';
            break;
            case 'department'://车间
                $api = '/api/getDepartment';
            break;
            case 'employee'://业务员
                $api = '/api/getEmp';
            break;
            case 'supplier'://供应商
                $api = '/api/getSupplier';
                break;
            case 'procureList'://采购订单
                $api = '/api/wms/getBillPurOrderList';
            break;
            case 'procureDetail'://采购订单明细
                $api = '/api/wms/getBillPurOrder';
            break;
            case 'getBillSEOutStockList'://发货通知单列表
                $api = '/api/wms/getBillSEOutStockList';
            break;
            case 'getBillSEOutStock'://发货通知单明细
                $api = '/api/wms/getBillSEOutStock';
            break;
            case 'getIcStockbill'://供应链单据明细
                $api = '/api/wms/getIcStockbill';
            break;
            case 'getIcStockList'://供应链单据列表
                $api = '/api/wms/getIcStockList';
            break;
            case 'getIcmoList'://生产任务单列表-材料清单列表
                $api = '/api/wms/getIcmoList';
            break;
            case 'getPPBOM'://生产任务单列表-材料清单明细
                $api = '/api/wms/getPPBOM';
            break;
            case 'saveIcchange'://生成组件单
                $api = '/api/wms/saveIcchange';
            break;
            case 'getIcchange'://组件单明细
                $api = '/api/wms/getIcchange';
            break;
            case 'getMaterialRequest'://领料申请
                $api = '/api/wms/getMaterialRequest2';
            break;
        }
        return self::kiscurl($api, $data, $pageflag,$logflag);
    }
    
    /**
     * 接口调用
     * @param string $api /api/u8base/get_cInv
     * @param array $data
     * return array
     */
    public static function kiscurl($api,$data = [],$pageflag = false,$logflag = true)
    {
        if(!$api){
            exception('调ERP-API参数错误');
        }
        
        // if(!config('site.backu8')){
        //     Log::info('KIS回写-WMS平台关闭调KIS','KIS回写-API');
        //     return false;
        // }

        $url = config('site.back_kis_host');
        if(!$url){
            exception('WMS配置缺失');
        }

        // 定义要读取的远程文件 URL
		$check_msg = (new self)->checkApi($url.'/api/Login/SignIn');
        if($check_msg){
            exception($check_msg);
        }
        
        if($logflag){
            Log::info($url.$api,'KIS回写-API');
            Log::info($data,'KIS回写-提交参数-');
        }
        
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url . $api);
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);//post
        
        //设置头部
        if($api == '/api/Login/SignIn'){
            $headers = [
                'Content-Type: application/json',
            ];
        }else{
            $token = self::getToken();
            if(!$token){
                exception('获取token失败');
            }
            $headers = [
                'Content-Type: application/json',
                'Authorization:Bearer '.$token
            ];
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $data = json_encode($data);
        
        if($data=='[]'){
            $data = '{}';
        }
        //Log::info($data,'KIS回写-提交参数-json_encode');
        
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置cURL允许执行的最长秒数
        
        //https请求 不验证证书和host
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $dataRes = curl_exec($ch);
        curl_close($ch);
        
        if($logflag){
            Log::info($dataRes,'KIS回写-返回结果-');
        }
        //myLog('KIS回写-返回结果',$data);
        
        if(!$dataRes){
            //exception('调ERP-API返回异常,请稍后再试');
            Log::info($dataRes,'KIS回写-返回结果1');
            exception('调ERP-API网络异常,请稍后再试');
        }
        
        $res = json_decode($dataRes,true);
        if($pageflag){
            //有翻页
            if(!isset($res['data_item'])){
                $message = '调ERP-API返回data_item解析异常';
                if(isset($res['Message'])){
                    $message = $res['Message'];
                }
                Log::info($dataRes,'KIS回写-返回结果2');
                exception($message);
            }
            return $res;
        }else{
            if(!isset($res['code'])){
                $message = '调ERP-API返回解析异常';
                if(isset($res['Message'])){
                    $message = $res['Message'];
                }
                if(isset($res['Errorcode'])){
                    $message = $res['message'];
                }
                Log::info($dataRes,'KIS回写-返回结果3');
                exception($message);
            }
            
            if($res['code']){
                //非0，失败,有可能重复调返回成功调用的记录，里面带单号
                //$strSubject = "处理失败,调ERP-API失败材料出库单P2OUT231101001已同步成功,KIS单据号[MD002231100001]";
                $u8code = '';
                if(isset($res['msg'])){
                    //{"code":9000,"data":null,"msg":"单据已经同步，请勿重复生成![CHG000779]"}
                    if(stripos($res['msg'],'请勿重复生成')>0){
                        //匹配单号出来
                        $strPattern = "/(?:\[)(.*)(?:\])/i";
                        preg_match_all($strPattern, $res['msg'], $arrMatches);
                        if(isset($arrMatches[1][0])){
                            $u8code = $arrMatches[1][0];
                        }
                    }
                }
                
                if($u8code){
                    //重试调接口，更新本地
                    $res['data']['cCode'] = $u8code;
                }else{
                    //获取token,成功返回 ["code"] => int(200)
                    //不进入失败抛异常
                    if($api != '/api/Login/SignIn'){
                        Log::info($dataRes,'KIS回写-返回结果4');
                        exception('调ERP-API失败'.$res['msg']);
                    }
                }
            }
            
            if(!$res['data']){
                if($res['msg'] == 'success'){
                    $res['data'] = [];
                }else{
                    Log::info($dataRes,'KIS回写-返回结果5');
                    exception('调ERP-API失败,返回data是null');
                }
            }
            
            //{"code":0,"data":{"cVal":1,"cCode":"HNWIN000699"},"msg":"新增外购入库单成功[HNWIN000699]!"}
            return $res['data'];
        }
    }

    //判断api接口是否通
    public function checkApi($url){
        // 要 POST 发送的数据
        $postData = [
            'username' => 'test',
        ];
        // 将数组格式的数据转换为 URL 编码的字符串
        $postDataEncoded = http_build_query($postData);
        // 创建一个 HTTP 上下文流，设置为 POST 请求
        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                            "Content-Length: " . strlen($postDataEncoded) . "\r\n",
                'content' => $postDataEncoded,
                'timeout' => 2 // 设置超时时间为 1 秒
            ]
        ]);
        // 使用上下文流发送 POST 请求并获取响应
        $msg = '';
        try{
            file_get_contents($url, false, $context);
        }catch(Exception $e){
            Log::error('调ERP-API:'.$e->getMessage());
            $msg = '调ERP-API超时,请检查网络';
        }
        return $msg;
    }
}

